import axios from 'axios'
import { getToken } from '@/utils/auth'
import { msgError } from '@/utils/message'
import router from '@/router'

const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: import.meta.env.VITE_APP_BASE_API,
    // 超时
    timeout: 30000
})

// request拦截器
service.interceptors.request.use((config: any) => {
    const isToken = (config.headers || {}).isToken === false
    if (getToken() && !isToken) {
        config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  }, (error: any) => {
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use((res: any) => {
        const data: any = res.data
        if(data.code == 200) {
            return Promise.resolve(data)
        }
        if(data.code == 401) {
            msgError(data.msg)
            return;
        }
        msgError(data.msg)
        return Promise.reject(data)
    },(error: any) => {
        return Promise.reject(error)
    }
)

export default service